package com.gaojiawei.review;

public class ReviewMsg {
    public static void main(String[] args) {

    }

    public static ListNode reverseKGroup(ListNode head,int k){
        if(head == null || head.next == null){
            return head;
        }

        ListNode start = head;
        ListNode end = findKGroupNode(start,k);
        if(end == null){
            return head;
        }
        head = end;
        reverse(start,end);
        ListNode lastEnd = start;
        while (lastEnd.next != null){
            start = lastEnd.next;
            end = findKGroupNode(start,k);
            if(end == null){
                return head;
            }
            reverse(start,end);
            lastEnd.next = end;
            lastEnd = start;

        }


        return head;
    }


    public static void reverse(ListNode start,ListNode end){
        if(start == null ||end == null){
            return;
        }
        end = end.next;
        ListNode pre = null;
        ListNode cur = start;
        ListNode next = null;
        while(cur != end){
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        start.next = end;
    }


    public static ListNode findKGroupNode(ListNode head,int k){
        while(--k != 0 && head != null){
            head = head.next;
        }
        return head;
    }



    public static class ListNode{

        ListNode next;
    }
}
